<template>
  <div style="background:#fff;padding:20px">
    <!-- 条件搜索的表单 -->
    <div>
      <el-form :inline="true">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字">
              <el-input
                v-model="searchObj.keyword"
                placeholder="用户名、姓名、手机号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dates"
                type="daterange"
                range-separator="To"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                :size="size"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </div>
    <!-- 新增用户按钮 -->
    <div>
      <el-button type="success" size="small" @click="handleShowSaveDialog">
        添加
      </el-button>
    </div>
    <!-- 用户分页列表表格 -->
    <div>
      <el-table :data="users" stripe style="width: 100%">
        <el-table-column prop="username" label="用户名" width="100" />
        <el-table-column prop="name" label="姓名" width="80" />
        <el-table-column prop="phone" label="手机" width="150" />
        <el-table-column prop="avatar" label="头像" #default="scope">
          <img :src="scope.row.avatar" alt="" style="width:40px;height:40px;" />
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleShowAssignRoleDialog(scope.row)"
            >
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:20px;text-align:center">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[1, 2, 3, 4, 5]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="initPageData"
          @current-change="initPageData"
        />
      </div>
    </div>

    <!-- 新增/修改用户的对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加或修改">
        <el-form :model="user">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="user.username" autocomplete="off" />
          </el-form-item>
          <el-form-item label="用户头像" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadPath"
              :show-file-list="false"
              :headers="headers"
              :data="{ module: 'avatar' }"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-error="handleAvatarError"
            >
              <img v-if="user.avatar" :src="user.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item
            label="密码"
            v-if="!user.id"
            :label-width="formLabelWidth"
          >
            <el-input v-model="user.password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="user.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机" :label-width="formLabelWidth">
            <el-input v-model="user.phone" autocomplete="off" />
          </el-form-item>
          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input v-model="user.description" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveOrUpdateUser">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 分配角色对话框 -->
    <div>
      <el-dialog v-model="assignRoledialogFormVisible" title="分配角色">
        <el-form>
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="user.username" disabled autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色列表" :label-width="formLabelWidth">
            <el-checkbox-group v-model="checkRolesList">
              <el-checkbox
                v-for="role in roles"
                :key="role.id"
                :label="role.id"
                :value="role.id"
                :checked="role.checked"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="assignRoledialogFormVisible = false">
              取消
            </el-button>
            <el-button type="primary" @click="assignRoles2User">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import {
  GetUserPage,
  GetUsers,
  GetUserById,
  UpdateUser,
  DeleteUser,
  SaveUser,
  AssignRoles2User,
} from '@/api/sysUser'
import { GetRolesAndIsChecked } from '@/api/sysRole'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApp } from '@/pinia/modules/app'
//表格：分配角色按钮事件函数
const handleShowAssignRoleDialog = async row => {
  //0、清除之前选中的缓存
  checkRolesList.value = []
  roles.value = []
  //1、查询所有的角色和已分配的角色回显
  const { data } = await GetRolesAndIsChecked(row.id)
  roles.value = data.items
  //2、弹出对话框
  user.value = row
  assignRoledialogFormVisible.value = true
}
//分配角色对话框属性 和函数
const assignRoledialogFormVisible = ref(false)
const roles = ref([])
const checkRolesList = ref([])
//分配角色对话框：提交按钮事件函数
const assignRoles2User = async () => {
  //获取用户id
  // user.id
  //获取选中的要分配的角色id列表
  console.log(checkRolesList.value)
  //提交分配角色的请求
  await AssignRoles2User(user.value.id, checkRolesList.value)
  //关闭对话框
  ElMessage.success('分配角色成功')
  assignRoledialogFormVisible.value = false
}

//上传组件属性和函数:
const headers = { token: useApp().authorization.token } //上传组件请求携带的请求头
const uploadPath = 'http://localhost:8501/admin/system/file/upload'
const handleAvatarSuccess = (response, uploadFile) => {
  //文件上传成功后的回调: 响应报文状态码200时回调
  //response:表示上传成功的响应报文
  console.log(response)
  if (+response.code === 200) {
    ElMessage.success('文件上传成功')
    user.value.avatar = response.data.path
  } else {
    ElMessage.error(response.message)
  }
}
const beforeAvatarUpload = rawFile => {
  //文件上传之前的检查
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件过大，不能超过2MB!')
    return false
  }
  return true
}
const handleAvatarError = error => {
  //文件上传失败的回调:响应报文状态码非200时回调
  ElMessage.error('网络连接失败')
}
//条件搜索对象
const searchObj = ref({ keyword: null, begin: null, end: null })
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(0)
const users = ref([]) //数据列表
const dates = ref([]) //选择的日期数组
//页面渲染时加载分页数据
onMounted(() => {
  initPageData()
})
//加载分页数据的函数
const initPageData = async () => {
  const { data } = await GetUserPage(
    pageNum.value,
    pageSize.value,
    searchObj.value
  )
  users.value = data.page.list
  total.value = data.page.total
}
//重置按钮事件函数
const handleReset = () => {
  searchObj.value = {}
  pageNum.value = 1
  pageSize.value = 3
  initPageData()
}
//搜索按钮事件函数
const handleSearch = () => {
  //先判断是否有搜索的日期
  // console.log(dates.value)
  //处理查询日期条件
  if (dates.value && dates.value.length === 2) {
    searchObj.value.begin = dates.value[0]
    searchObj.value.end = dates.value[1]
  }
  //条件查询分页数据
  initPageData()
}
//表格：删除按钮事件函数
const handleDelete = row => {
  ElMessageBox.confirm(`是否删除用户【${row.username}】?`, '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await DeleteUser(row.id)
      if (+code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        initPageData()
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//新增按钮事件函数：显示对话框
const handleShowSaveDialog = () => {
  //清除缓存
  user.value = {}
  dialogFormVisible.value = true
}
//新增修改对话框的属性函数
const dialogFormVisible = ref(false)
const user = ref({})
const formLabelWidth = '120px'
//提交按钮事件函数
const handleSaveOrUpdateUser = () => {
  if (user.value.id) {
    //更新
    handleUpdateUser()
  } else {
    //新增
    handleSaveUser()
  }
}
//新增用户
const handleSaveUser = async () => {
  await SaveUser(user.value)
  ElMessage.success('新增成功')
  initPageData()
  dialogFormVisible.value = false
}
//更新用户
const handleUpdateUser = async () => {
  await UpdateUser(user.value)
  ElMessage.success('更新成功')
  initPageData()
  dialogFormVisible.value = false
}

//表格：修改按钮事件函数    回显要修改的数据
const handleEdit = async row => {
  const { data } = await GetUserById(row.id)
  user.value = data.item
  dialogFormVisible.value = true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
